package com.baidu.health.WebSocket;

import com.alibaba.fastjson.JSON;
import com.baidu.health.controller.CustomerController;
import com.baidu.health.mapper.TbFaqMapper;
import com.baidu.health.pojo.TbFaq;
import com.baidu.health.service.TbFaqServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/onLineService")
public class MyWebSocket {

    @Autowired
    TbFaqServiceImpl faqService;

    @Autowired
    CustomerController controller;

    @Autowired
    TbFaqMapper faqMapper;

    @Autowired
    RestHighLevelClient restHighLevelClient;

    // 全部在线会话 PS: 基于场景考虑 这⾥使⽤线程安全的Map存储会话对象。
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();
    private Session _session;
    @OnOpen
    public void onOpen(Session session) {
        this._session = session;
        onlineSessions.put(session.getId(), session);
        try {
            sendMessage(session,"你好！！！您想咨询什么问题！！！");
        }catch (Exception e) {
            log.error("onOpen", e);
        }
        log.info("有新连接加⼊，当前在线数为" + onlineSessions.size());
    }
    @OnClose
    public void onClose(Session session) {
        onlineSessions.remove(session.getId());
        log.info("有⼀连接关闭！当前在线数为" + onlineSessions.size());
    }
    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
//        sendMessageAll(session.getId() + ":" + message);
//        sendMessage(session,"您是要问："+ message);

        sendMessage(session,"您是要问："+ message);
        log.info("来⾃客户端 " + " 的消息:" + message);
    }
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("LoginResultWebSocket 发⽣错误");
        error.printStackTrace();
    }

    public void sendMessage(Session session, String message) throws
            IOException {
        session.getBasicRemote().sendText(message);
    }
    public void sendMessageAll(String message) {
        for(String key : onlineSessions.keySet()){
            Session session = onlineSessions.get(key);
            try {
                sendMessage(session, message);
            }
            catch (Exception e) {
                log.error("sendMessageAll", e);
            }
        }
    }

}
